<?php

namespace app\modules\user\forms\login;

use app\common\forms\BaseForm;
use app\common\services\CodeService;
use app\config\Constants;
use app\models\User;
use app\modules\user\services\UserService;

class MobileLoginForm extends BaseForm{

    public $mobile;
    public $code;

    /**
     * @var User
     */
    private $_user = false;

    public function rules()
    {
        return [
            ['mobile','required','message'=>\Yii::t("app","手机号不能为空")],
            ['code','required','message'=>\Yii::t("app","验证码不能为空")],
            ['code','verifyCode'],
        ];
    }

    //校验验证码
    public function verifyCode($attribute,$params){
        if(!CodeService::verifyCode($this->mobile,$this->$attribute)){
            $this->addError("code",\Yii::t("app","验证码错误"));
        }
    }

    public function login(){

        if ($this->validate()) {
            $user = $this->getUser();
            return \Yii::$app->getModule("user")->user->login($user);
        }
        return false;
    }

    /**
     * Finds user by [[mobile]]
     *
     * @return User
     */
    public function getUser(){
        if ($this->_user === false) {
            $this->_user = UserService::findInfoByCredential($this->mobile,Constants::PHONE);
            if(!$this->_user){
                $this->_user = UserService::create($this->mobile,Constants::PHONE);
            }
        }
        return $this->_user;
    }
}